<template>
  <div class="searchpage">
  	  <div class="backhome" @click="goback()"><span></span><img src="../../static/img/home_back.png"/></div>
      <div class="searchinput"><mt-search v-model="searchvalue" :autofocus="true" cancel-text="取消" placeholder=""></mt-search></div>
      <div class="hslist">
        <ul>
          <li v-for="item in historylist" @click="searchis(item.timeText)">
            <span class="ellipisis" v-text="item.timeText"></span>
          </li>
        </ul>
        <div @click="clearall()" v-show="showclearbtn">清除历史</div>
      </div>
  </div> 
</template>

<script>
import Mock from 'mockjs'

export default {
  name: 'searchpage',
  props : ['historypage'],
  data () {
    return {
      searchvalue:'',
      showclearbtn:false,
      result:[],
      historylist:[]
    }
  },
  watch: {
    /*searchvalue: function (val) {
    	var data = Mock.mock({
          // 属性 list 的值是一个数组，其中含有 1 到 10 个元素
          'list|1-20': [{
              // 属性 id 是一个自增数，起始值为 1，每次增 1
              'title|+1': '同仁堂',
              'value|+1' : 1
          }]
        })
        this.result = data.list;
    }*/
  },
  methods : {
    searchlist(){
      console.log('search');
      //搜索跳转列表在列表里面查询
      let val = this.searchvalue.replace(/\s/ig,'');
      let obj = {'val':val,'historypage': 'searchpage'};
      this.cachelocal(obj);
      this.$router.push({ name: 'druglist',query:obj});
    },
    //取消
    searchcancle(){

    },
    searchis(val){
      let obj = {'val':val,'historypage': 'searchpage'};
      this.$router.push({ name: 'druglist',query:obj});
    },
    cachelocal(obj){
      //获取输入框值去空
        let serchareaVal = obj.val;
        let getstorageData = localStorage.getItem("searchlist");
        //存缓存，超出10条就从队列顶部删除
        let storagelocaldata = (arr)=>{
            let timeTextObj = {};
            timeTextObj.timeText = serchareaVal;
            if(arr==undefined){
                let storagearr = [];
                storagearr.unshift(timeTextObj);
                localStorage.setItem("searchlist", JSON.stringify(storagearr));
            }else{
                arr.unshift(timeTextObj);
                if(arr.length>10){
                    arr.pop();
                }
                localStorage.setItem("searchlist", JSON.stringify(arr));
            }
        };
        if(serchareaVal==''){
            return;
        }
        //有重复的字段就不缓存
        if(getstorageData!=null&&getstorageData!=''){
            try { 
                let arr = eval('('+getstorageData+')');
                let isStore = true;
                $.each(arr, function (index, item) {
                    if(serchareaVal == item.timeText){
                        isStore = false;
                    }
                })
                if(isStore){
                    storagelocaldata(arr);
                }
            } catch (e) {
            }
            
        }else{
            storagelocaldata();
        }
    },
    showhistory(){
      let list = localStorage.getItem("searchlist");
      try{
        var obj = eval('('+list+')');
        if(obj.length>0){
          this.showclearbtn = true;
        }
        this.historylist = obj;
      }catch(e){

      }
    },
    clearall(){
      localStorage.setItem("searchlist", '');  //清缓存
      this.historylist = [];
      this.showclearbtn = false;
    },
    bindsearch(){
      $(".searchinput input").keydown(e=>{
          if(e.keyCode == '13') {
                this.searchlist();
          }
      });
    }
  },
  mounted(){
      //展示历史记录
      this.showhistory();
      //绑定软键盘搜索
      this.bindsearch();
  }
}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
  $grayback:#d9d9d9;
  $clearheightli:40px;
	.searchpage{
		.backhome{
			position: relative;
		    float: left;
		    height: 52px;
		    z-index: 1;
		    background-color: $grayback;
		    span{
		        height:100%;
		        display:inline-block;
		        vertical-align: middle;

		    }
		    img{
		    	vertical-align: middle;
		    }
		}
    .search{
      position: absolute;
      top: 0;
      right: 0;
      width: 15%;
      line-height: 52px;
      height:52px;
      background-color:$grayback;
      text-align: center;
    }
    .hslist{
      width:100%;
      top: 52px;
      position: absolute;
      background-color: #fefefe;
      >div{
        width:100%;
        height:$clearheightli;
        line-height:$clearheightli;
        border-bottom:1px solid #eeeeee;
      }
      ul{
        position:relative;
        li{
          text-align: left;
          height:$clearheightli;
          line-height:$clearheightli;
          border-bottom:1px solid #eeeeee;
          span{
            display: inline-block;
            width:80%;
            margin-left:10px;
          }
        }
      }
    }
	}
</style>
